﻿using FieldTools.Util;
using FieldTools.WebApi;
using FieldTools.WebApi._01Middleware;
using LogDashboard;
using Microsoft.AspNetCore.Mvc;
using Serilog;

namespace FieldTools.Client.WebApi
{
    public class StartUp
    {
        /// <summary>
        /// 打开服务端
        /// </summary>
        /// <param name="args"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task OpenServer(string[] args, CancellationToken token)
        {
            
            #region Serilog配置
            //var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                //.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
                .Build();

            //string logOutputTemplate = "{Timestamp:HH:mm:ss.fff zzz} || {Level} || {SourceContext:l} || {Message} || {Exception} ||end {NewLine}";
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                //.MinimumLevel.Override("Default", LogEventLevel.Information)
                //.MinimumLevel.Override("Microsoft", LogEventLevel.Error)
                //.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
                //.Enrich.FromLogContext()
                .WriteTo.Console(theme: Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme.Code)
                //.WriteTo.File($"{AppContext.BaseDirectory}Logs/.log", rollingInterval: RollingInterval.Day, outputTemplate: logOutputTemplate)
                .CreateLogger();

            #endregion


            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer()
                .AddSwaggerGen()
                .AddFxServicesMini()
                //.AddAutoMapperMini().
                //.AddLogging(builder => builder.AddFile());
                .Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true)
                .AddControllers(options =>
                {
                    options.Filters.Add<ValidFilterAttribute>();
                    options.Filters.Add<GlobalExceptionFilter>();
                })
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
                    options.SerializerSettings.GetType().GetProperties().ForEach(aProperty =>
                    {
                        var value = aProperty.GetValue(JsonExtention.DefaultJsonSetting);
                        aProperty.SetValue(options.SerializerSettings, value);
                    });
                });
            builder.Services.AddLogDashboard();
            builder.Host.UseSerilog(Log.Logger, dispose: true);

            //builder.Services;
            Log.Information("Starting web host");
            var app = builder.Build();
            //允许body重用
            app.Use(next => context =>
            {
                context.Request.EnableBuffering();
                return next(context);
            })
                .UseRouting()
                .UseMiddleware<CorsMiddleware>()//跨域
                .UseDeveloperExceptionPage()
                .UseStaticFiles(new StaticFileOptions
                {
                    ServeUnknownFileTypes = true,
                    DefaultContentType = "application/octet-stream"
                })
                .UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                })
                .UseCalculateExecutionTime();
            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            app.UseAuthorization();
            app.UseSerilogRequestLogging();
            app.MapControllers();
            app.UseLogDashboard();

            await app.RunAsync(token);
        }
    }
}
